<?php
/**
 * Base on the request URL and role/permisson of current user, forward the user
 * to the login page if the user have not logged in 
 */
class Application_Plugin_AclManager extends Zend_Controller_Plugin_Abstract 
{

	public function preDispatch(Zend_Controller_Request_Abstract $request) 
	{
		//得在ACL之前运行
		$userM = new Application_Model_DbTable_User();
		$userM->doCookieLogin();
		try {
			$isAllowed = Application_Service_Acl::isUserAllowedS();
			if (!$isAllowed) {
				//Log::w("[acl deny]\n". print_r($_REQUEST, 1) . print_r($_SERVER) . print_r($_SESSION, 1));
				$this->getResponse()->setHttpResponseCode(403);
				
				$message = "抱歉，您没有权限访问这个操作。";
				if (!$_SESSION['shoprr']['company_id']) $message .= "（您还没有登录，请登录后尝试）";
				$this->showError($message);
			}
		} catch (DataInvalidException $e) {
			$this->showError($e->getMessage());
		}
		
		return;
		
		
	
		$M = $this->getRequest()->getModuleName();
		$C = $this->getRequest()->getControllerName();
		$A = $this->getRequest()->getActionName();
		$acl = Application_Service_Acl::getInstance();
		
		//根据需要在指定的url上停止使用ACL，支持*通配符。
		$noAclMList = array(
			"*/*/*", //all are disabled BY Long 08222012
			"app/*/*",
			"shop/login/*",
			"shop/index/index",
			"default/menu/*",
			"default/superadmin/*",
			"default/*/*",
			"shop/*/*",
			"padpos/*/*",
			"help/*/*",
			"notice/*/*",
			"restaurant/*/*",
			"electroniccard/*/*",
			"webservice/*/*",
			"henglong/*/*"
		);

		//echo "this is test<br>" , "{$M}/{$C}/{$A}";
		//print_r(!$this->isin("{$M}/{$C}/{$A}", $noAclMList));
		//die("xxxx");
		//下面拦截并判断当前用户是否有权限访问此控制器
		if(!$this->isin("{$M}/{$C}/{$A}", $noAclMList)){
			try {
				//$acl = Application_Service_Acl::getInstance();
				$roleModle = new Application_Model_DbTable_Role();
				$role = $roleModle->itemsByUser($_SESSION['shoprr']['admin_bh'],$_SESSION['shoprr']['company_id']);
				$roleArr =array();
				foreach($role as $r){
					$roleArr[]=$r['role_id'];
				}
				//print_r($roleArr);
				//echo ($acl->isMyAllow($M,$roleArr,$C,$A))?"Y":"F";
				if(!$acl->isMyAllow($M,$roleArr,$C,$A)){
					//这里应该抛出403错误
					$this->getRequest()->setModuleName("default");
					$this->getRequest()->setControllerName("error");
					$this->getRequest()->setActionName("index");
					//throw new Exception("403 Access diny");
					
				}
			}catch (Exception $e){
				throw  $e;
			}
			
		}
	}
	
	/**
	 * 参数0是否在参数1的数组中，支持通配符*
	 * Enter description here ...
	 * @param String $url
	 * @param Array $arr
	 * @return Boolean
	 */
	private function isin($url,$arr){
		try {
			$rs=FALSE;
			if(!is_array($arr)){
				$arr = array($arr);
			}
			if(in_array($url, $arr)){
				return TRUE;
			}else{
				$urlArr = explode("/", $url);
				//print_r($urlArr);
				foreach ($arr as $ruler){
					$rulerArr = explode("/", $ruler);
					//print_r($rulerArr);
					$u = $urlArr;
					$r = $rulerArr;
					if(($u[0] == $r[0] || $r[0] == "*") && ($u[1] == $r[1] || $r[1] == "*") && ($u[2] == $r[2] || $r[2] == "*")){
						return TRUE;
					}
				}
				return FALSE;
			}
		}catch (Exception $e){
			return FALSE;
		}
	}
	
	public function showError($message, $httpResponseCode = 200) {
		$responseText;
		if ($this->getRequest()->isXmlHttpRequest()) {
			$responseText = json_encode(array(
				'status' => 'error',
				'message' => $message,//如果放在这儿处理，可以容易的获取权限名称
				'success' => 0,
				'error' => $message
			));
		} else {
			$responseText = $message;
		}
		echo $responseText;exit();
		//$this->getResponse()->setBody($responseText);
	}
}
